<template>
          <el-dialog  title="创建航线" v-model="dialogFormVisible" >

          <el-form :model="form">

            <el-form-item label="航线名" label-width="90px">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="航线结束后" label-width="90px" >
              <el-select v-model="form.finishAction" placeholder="航线结束动作">
                <el-option label="悬停" value="hover"></el-option>
                <el-option label="返航" value="goHome"></el-option>
                <el-option label="降落" value="land"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="失去信号后" label-width="90px" >
              <el-select v-model="form.executeRCLostAction" placeholder="失控后动作">
                <el-option label="悬停" value="hover"></el-option>
                <el-option label="返航" value="returnToHome"></el-option>
                <el-option label="降落" value="land"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="安全高度" label-width="90px">
              <el-input-number v-model="form.takeOffSecurityHeight" :min="0" :max="1500" ></el-input-number>           

            </el-form-item>
            <el-form-item label="速度变化率" label-width="90px">
              <el-input-number v-model="form.globalTransitionalSpeed" :min="1" :max="50" ></el-input-number>           

            </el-form-item>
            <el-form-item label="默认速度" label-width="90px">
              <el-input-number v-model="form.autoFlightSpeed" :min="1" :max="1500" ></el-input-number>           

            </el-form-item>
            <el-form-item label="转弯方式" label-width="90px" >
              <el-select v-model="form.globalWaypointTurnMode" placeholder="航点转弯方式">
                <el-option label="平滑悬停" value="toPointAndStopWithSmoothCurvature"></el-option>
                <el-option label="急转悬停" value="toPointAndStopWithDiscontinuityCurvature"></el-option>
                <el-option label="平滑连续" value="toPointAndContinueWithSmoothCurvature"></el-option>
                <el-option label="急转连续" value="toPointAndContinueWithDiscontinuityCurvature"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="creatLineFile">确 定</el-button>
          </div>
          </el-dialog>
      <el-scrollbar class="livingview">
        <!-- 按钮 -->
        <div style="display: flex;justify-content: space-around;flex-wrap: wrap;">
          <el-button  @click="dialogFormVisible = true">创建航线文件</el-button>
          <div v-if="creatXmlFlag">
            <el-button v-if="setPoint" @click="changeSetPoint">放置点</el-button>
            <el-button v-else="setPoint" @click="changeSetPoint">取消放置点</el-button>
            <!-- <el-button  @click="gg">取ddd点</el-button> -->
            <el-button  @click="finifshCreatFile">确定创建</el-button>
          </div>
        </div>



        <!-- 航线点展示 -->
        <el-collapse accordion>
      <div v-for="(item, index) in lindata.features"  :key="item.id">
        
          <el-collapse-item :title="'航线点'+(index+1)" :name="item.id" @click="changClickPoint(item)">
            <div class="PointPanel">
              <div class="slider-demo-block">
                <!-- //拖拽条 -->
                <el-slider v-model="item.properties.h" vertical height="150px" :max="500"/>
                <el-slider v-model="item.rotation.z" vertical height="150px" :min="-90" :max="-10" @change="turnUpRot(item)" />
                <div style="width: 140px;float: right;padding-right:12px">
                  <el-slider  v-model="item.rotation.y" :min="-180" :max="180"  @change="turnView(item)"/>
                  <el-button type="" class="buttonPoint" @click="turnViewButton(item)">进入点控制</el-button>
                  <el-button type="" @click="addAngleAction(item)">增加旋转动作</el-button>
                  <el-button type="" @click="addtakePhotoAction(item)">增加拍摄动作</el-button>

                  <!-- <el-slider  v-model="item.rotation.x" :min="0" :max="180"/> -->
                </div>
              </div>
            </div>
          </el-collapse-item>
        

      </div>
      </el-collapse>
      </el-scrollbar>
<!-- zoom焦距   center中心点   pitch倾斜角度  rotation旋转角度      
      :dragEnable="false"
      :keyboardEnable="false"
      :scrollWheel="false"
      
    -->
  <div class="map-page-container" style="height: 100%;width: 100%;">
    <el-amap
      view-mode="3D"
      :pitchEnable="false"
      :dragEnable="dragFlage"
      :pitch="pitch"
      :show-label="false"
       v-model:center="center"
      :zoom="zoom"
      :height="centerHeight"
      :rotation="rotation"
      :doubleClickZoom="true"

      @click="clickMap"
      @init="initMap"
    >
    
    <el-amap-loca @init="initLoca">
        <el-amap-loca-pulse-line
          :visible="visible"
          :sourceData="pointLineData"
          :layer-style="pulesStyle"
          :visible-duration="500"
        />
      </el-amap-loca>
      <el-amap-loca @init="initLoca" @click="changClickPoint2">
        <el-amap-loca-laser
          :visible="visible"
          :sourceData="lindata"
          :layer-style="layerStyle"
          :visible-duration="500"


        />
      </el-amap-loca>
      <el-amap-layer-three
        :hdr="hdrOptions"
        :create-canvas="true"
        @init="initLayer"
      >
        <el-amap-three-light-ambient
          color="rgb(255,255,255)"
          :intensity="0.6"
        />
        <el-amap-three-light-directional
          color="rgb(255,0,255)"
          :intensity="1"
          :position="{x:0, y:1, z:0}"
        />
        <el-amap-three-light-hemisphere
          color="blue"
          :intensity="1"
          :position="{x:1, y:0, z:0}"
        />
        <el-amap-three-light-spot :position="{x:0, y:1, z:0}" />
        <text v-if="pointnum">

          <el-amap-three-gltf
          @click="kk"
            :url="'src/assets/aaa.glb'"
            :position="lindata.features[modelLocal].geometry.coordinates"
            :scale="[10,10,10]"
            :visible="visible"
            :height="lindata.features[modelLocal].properties.h"
            :useModelCache="true"
            :rotation="lindata.features[modelLocal].rotation"
            :moveAnimation	= "{duration: 400, smooth: true}"

            />
            <el-amap-three-gltf
            :url="'src/assets/table.glb'"
            :position="lindata.features[modelLocal].geometry.coordinates"
            :scale="[10,10,10]"
            :visible="visible"
            :height="lindata.features[modelLocal].properties.h"
            :useModelCache="true"
            :rotation="pisRotation"
            :moveAnimation	= "{duration: 400, smooth: true}"

            />
            
        </text>
      </el-amap-layer-three>
    </el-amap>


  </div>

</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import {ref,computed,reactive} from "vue";
import {ElAmap} from "@vuemap/vue-amap";
import { useLinePoint } from '@/hooks/use-pline-line'
import {usePlineXml} from '@/hooks/use-pline-creatXml'
import {
  ElAmapLayerThree,
  ElAmapThreeGltf,
  ElAmapThreeLightAmbient,
  ElAmapThreeLightDirectional,
  ElAmapThreeLightHemisphere,
  ElAmapThreeLightSpot
} from '@vuemap/vue-amap-extra';
import { importKmzFile } from '@/api/wayline'
import {RenderPass} from 'three/examples/jsm/postprocessing/RenderPass.js';
import {ShaderPass} from 'three/examples/jsm/postprocessing/ShaderPass.js';
import {DotScreenShader} from 'three/examples/jsm/shaders/DotScreenShader.js';
import amapApiLoader from "@vuemap/vue-amap/es/services/amap-api-loader.js";
let setPoint = ref(true)
let pointnum = ref(0)//模型出现在哪一个数组位置
let modelLocal = ref(0)
let useGMapLineHook = useLinePoint()
let creatPlineXml = usePlineXml()
const baseUrl = "https://vue-amap.guyixi.cn/";
const pitch = ref(50)//pitch倾斜角度
const zoom = ref(18);//zoom焦距
const center = ref([116.45981, 39.992648,100000]);
const rotation = ref(0)//rotation旋转角度
const oldZoom = ref();
const oldCenter = ref([]);
const oldRotation = ref(0)
const oldPitch = ref();
const centerHeight = ref(100)
const visible = ref(true);
const turnRotFlag = ref(false)
const dragFlage = ref(true)
const dialogFormVisible = ref(false)
const creatXmlFlag = ref(false)
const layerStyle = ref({
  unit: 'meter',
  height: (i, feat) => {
      return feat.properties.h ;
  },
  color: 'rgba(30,215,196, 1)',
  lineWidth: 3,
  trailLength: 5000,
  repeat: 0
})
const pisRotation = computed(() => {
      // 回调函数必须return，结果就是计算的结果
      // 如果计算属性依赖的数据发生变化，那么会重新计算
      let oldRot = lindata.value.features[modelLocal.value].rotation
      return  {x:oldRot.x,y:oldRot.y,z:oldRot.z-90}
      
    })
const changClickPoint2 = (loca: any)=>{//点击地图上的标记点线
  if(loca.length>0)
    modelLocal.value = loca[0].sr-1
  
}
const changClickPoint = (post:any)=>{//点击左侧的风琴
  modelLocal.value = post.id
  center.value = post.geometry.coordinates
}
const changeSetPoint = ()=>{//是否增加点
  setPoint.value = !setPoint.value
}
const turnViewButton = (point :any)=>{//点击并改变地图视角
  turnRotFlag.value = !turnRotFlag.value
  if(turnRotFlag.value){
    oldRotation.value = rotation.value
    oldPitch.value = pitch.value
    rotation.value=point.rotation.y-90
    pitch.value = point.rotation.z+90
    dragFlage.value=false
  }
  else{
    dragFlage.value=true
    rotation.value = oldRotation.value
    pitch.value = oldPitch.value
  }
  
}
const addAngleAction = (point:any)=>{ //增加云台旋转动作
  const action = creatPlineXml.getActionAngle(point)
  point.action.push(action)
  console.log( lindata.value.features);
  ElMessage.success('添加动作成功')
  
}
const addtakePhotoAction = (point:any)=>{ //增加云台旋转动作
  const action = creatPlineXml.getTakePhotoAngle(point)
  point.action.push(action)
  ElMessage.success('添加动作成功')
}

const finifshCreatFile = ()=>{
  creatPlineXml.finifshCreatFile(lindata.value.features)
  ElMessage.success('航线创建成功')
}
const turnUpRot = (point :any)=>{
  if(turnRotFlag.value){
    pitch.value = point.rotation.z+90

  }

}
const turnView = (point :any)=>{//滑动改变地图视角

  if(turnRotFlag.value){
    rotation.value=point.rotation.y-90

  }
}
const form =reactive({
    name: '',//航线名字
    executeRCLostAction: 'returnToHome',//失控后动作
    finishAction: 'goHome',//航线结束动作
    takeOffSecurityHeight: 10,//安全高度
    globalTransitionalSpeed: 8,//速度变化率
    autoFlightSpeed: 7,//默认速度
    globalWaypointTurnMode: 'toPointAndContinueWithSmoothCurvature',//拐弯方式
  })
const creatLineFile = ()=>{
  if(form.name){
    creatXmlFlag.value = true
    creatPlineXml.creatLineXml(form)
    dialogFormVisible.value = false;
  }
  
  else{
    ElMessage.error('未设置航线名')
  }



}

const lindata = ref({//点位置与旋转
        type: 'FeatureCollection',
        features: [
            // {
            //     id:0,
            //     geometry: {
            //         coordinates: [116.467041, 39.997771],
            //         type: 'Point',
            //     },
            //     type: 'Feature',
            //     properties: {
            //         h: 110,
            //     },
            //     rotation:{
            //       x:0,
            //       y:0,
            //       z:30
            //     }
            // }
            // {
            //   id:1,

            //     geometry: {
            //         coordinates: [116.45981, 39.992648],
            //         type: 'Point',
            //     },
            //     type: 'Feature',
            //     properties: {
            //         h: 400,
            //     },
            //     rotation:{
            //       x:0,
            //       y:0,
            //       z:30
            //     }
            // },    
        ]}
    )
const pointLineData = ref({//航信的数据
    type: "FeatureCollection",
    features: [
]
      
})
interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: string;
  url?: string;
}
interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}



const headColors = ['#ECFFB1', '#146968', '#146968', '#146968', '#146968', '#146968', '#146968', '#146968'];
const trailColors = [
  'rgba(255,178,6, 0.2)',
  'rgba(255,178,6, 0.2)',
  'rgba(20,105,104, 0.2)',
  'rgba(20,105,104, 0.2)',
  'rgba(20,105,104, 0.2)',
  'rgba(20,105,104, 0.2)',
  'rgba(20,105,104, 0.2)',
  'rgba(20,105,104, 0.2)',
];
const pulesStyle = ref({
  altitude: 0,
  lineWidth: (_, feature) => feature.properties.lineWidthRatio * 4 + 1,
  headColor: (_, feature) => headColors[feature.properties.type],
  trailColor: (_, feature) => trailColors[feature.properties.type],
  interval: 0.5,
  duration: 2000,
})

const clickMap = (e) => {//点击地图增加标记
  if(!setPoint.value){

    let fea = lindata.value.features
    let point = useGMapLineHook.newPoint(e.lnglat.lng,e.lnglat.lat,pointnum.value)//創建新點
    fea.push(point)
    if(pointnum.value>=1){
      let line = useGMapLineHook.newLine(point.geometry.coordinates,fea[fea.length-2].geometry.coordinates,pointnum.value)
      pointLineData.value.features.push(line) 
      fea[fea.length-2].rotation.y = line.angle
      fea[fea.length-1].rotation.y = line.angle
    }
    
    pointnum.value+=1
    console.log('click map: ', e);
  }
}
const initMap = (map) => {
  console.log('init map: ', map);
}

const initLoca = (loca: any) => {
  loca.animate.start();

  
}

// const position = ref([116.45981, 39.992648]);
// const rotation = ref({x: 90, y: 0, z: 0});
// const moveAnimation = ref({duration: 1000, smooth: true});
// const carAngle = ref(90);
const hdrOptions = ref({
  urls: ['px.hdr', 'nx.hdr', 'py.hdr', 'ny.hdr', 'pz.hdr', 'nz.hdr'],
  path: `src/assets/`
});
const initLayer = (layer) => {
  const renderPass = new RenderPass(layer.getScene(), layer.getCamera());
  layer.addPass(renderPass);
  const effect1 = new ShaderPass(DotScreenShader);
  effect1.uniforms['scale'].value = 4;
  layer.addPass(effect1);
}
const init = (object, $vue) => {
  $vue.$$startAnimations();
}
// const initCar = () => {
//   startCar();
// }
// const startCar = () => {
//   carInterval = setInterval(() => {
//     const lng = carPosition.value[0] + Math.random() * 0.0001;
//     const lat = carPosition.value[1] + Math.random() * 0.0001;
//     const newPosition = [lng, lat];
//     const angle = Math.random() * 360
//     carPosition.value = newPosition;
//     carAngle.value = angle;
//   }, 1000)
// }
// const stopCar = () => {
//   clearInterval(carInterval);
// }
</script>

<style scoped>
 .livingview {
     position: absolute;
     padding: 5px;
     z-index: 99;
     height: 100%;
     width: 245px;
     box-sizing: border-box;
     background-color: rgb(255, 255, 255);
     display: flex;
     flex-direction: column;
   
     flex-wrap: nowrap;
 }
 .PointPanel{
  padding-top: 12px;
  background-color: rgb(247, 247, 247);
 }
 .buttonPoint{
  margin-left: 18px;
  margin-bottom: 10px
 }
</style>